package com.innovation.chengzhangriji.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.StateSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.BabyAllResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

public class BabynoticeActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener {
    private MyAdapter myAdapter;
    private BabyAllResponse[] info;
    private ArrayList<BabyAllResponse> list;
    private int length;
    private boolean isAdmin;
    private ListView listView;
    private DisplayImageOptions options;
    private LoginInfo loginInfo;
    private BabyAndParent babyAndParent;
    private CuteToolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_babynotice);

        toolbar = (CuteToolbar) findViewById(R.id.babynotice_toolbar);
        toolbar.setOnClickCuteToolbarListener(this);

        myAdapter = new MyAdapter();
        list = new ArrayList<BabyAllResponse>();
        listView = (ListView) findViewById(R.id.listview_babynotice);
        listView.setAdapter(myAdapter);

        loginInfo = Config.getLoginInfo(BabynoticeActivity.this);
        final String userId = loginInfo.getUserID();
        final int babyId = loginInfo.getBabyID();
        babyAndParent = DatabaseManager.getInstance(BabynoticeActivity.this).queryBabyAndParent(userId, babyId);
        isAdmin = babyAndParent.getRole() == 2;

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isAdmin) {
                    Intent intent = new Intent(BabynoticeActivity.this, BabyNoticeDetailActivity.class);
                    Gson gson = new Gson();
                    String permission = gson.toJson(list.get(position));
                    intent.putExtra("permission", permission);
                    intent.putExtra("length", length);
                    Gson gson2 = new Gson();
                    String sInfo = gson2.toJson(info);
                    intent.putExtra("info", sInfo);
                    startActivityForResult(intent, 1000);
//                    startActivity(intent);
                } else {
                    Intent intent = new Intent(BabynoticeActivity.this, BabyNoticeDetailNotadminActivity.class);
                    Gson gson = new Gson();
                    String permission = gson.toJson(list.get(position));
                    intent.putExtra("permission", permission);
                    intent.putExtra("length", length);
                    Gson gson2 = new Gson();
                    String sInfo = gson2.toJson(info);
                    intent.putExtra("info", sInfo);
                    startActivity(intent);
//                    tipShow("您不是大家长");
//                    if (list.get(position).getPhone() == loginInfo.getPhone()){
//                        Intent intent = new Intent(BabynoticeActivity.this,BabyNoticeDetailActivity.class);
//                        startActivity(intent);
//                    }
                }
            }
        });


        setOptions();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1000) {
                if (data != null && data.getBooleanExtra(Config.EXTRA_CAN_BACK, true)) {
                    setResult(RESULT_OK, data);
                    finish();
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestBabyAll();
    }

    private void requestBabyAll() {
        LoginInfo loginInfo = Config.getLoginInfo(BabynoticeActivity.this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        final String userId = loginInfo.getUserID();
        final int babyId = loginInfo.getBabyID();
        BabyAndParent babyAndParent = DatabaseManager.getInstance(BabynoticeActivity.this).queryBabyAndParent(userId, babyId);
        isAdmin = babyAndParent.getRole() == 2;

        // 判断网络
        if (!isNetworkConnect(BabynoticeActivity.this)) {
            Parent[] parents = DatabaseManager.getInstance(BabynoticeActivity.this).queryParent(babyId);
            if (parents == null || parents.length == 0) {
                return;
            }
            BabyAllResponse[] responses = new BabyAllResponse[parents.length];
            length = responses.length;
            info = responses;
            list.clear();
            for (int i = 0; i < parents.length; i++) {
                responses[i] = new BabyAllResponse();
                responses[i].setType(parents[i].getType());
                responses[i].setUserId(parents[i].getParentId());
                responses[i].setUser(parents[i].getUser());
                responses[i].setName(parents[i].getName());
                responses[i].setPhone(parents[i].getPhone());
                responses[i].setServerTS(parents[i].getServerTS());
                responses[i].setMessage(parents[i].getMessage());
                responses[i].setPath(parents[i].getPath());
                responses[i].setNickName(parents[i].getNickName());
                Auth auth = new Auth();
                auth.setRole(parents[i].getRole());
                auth.setPermission(parents[i].getPermission());
                auth.setRange(parents[i].getRange());
                responses[i].setAuth(auth);
                list.add(responses[i]);
            }
            myAdapter.notifyDataSetChanged();
            return;
        }
        Client.requestBabyAll(BabynoticeActivity.this, phone, token, babyId, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                JsonObject object = value.getAsJsonObject();
                JsonArray jsonArray = object.getAsJsonArray("Messages");
                BabyAllResponse[] responses = get(jsonArray.toString(), BabyAllResponse[].class);
                if (responses == null) {
                    return;
                }
                list.clear();
                length = responses.length;
                info = responses;
                Parent[] parents = new Parent[responses.length];
                for (int i = 0; i < responses.length; i++) {
                    list.add(responses[i]);
                    parents[i] = new Parent();
                    parents[i].setBabyId(babyId);
                    parents[i].setType(responses[i].getType());
                    parents[i].setParentId(responses[i].getUserId());
                    parents[i].setUser(responses[i].getUser());
                    parents[i].setName(responses[i].getName());
                    parents[i].setPhone(responses[i].getPhone());
                    parents[i].setServerTS(responses[i].getServerTS());
                    parents[i].setMessage(responses[i].getMessage());
                    parents[i].setPath(responses[i].getPath());
                    parents[i].setNickName(responses[i].getNickName());
                    parents[i].setRole(responses[i].getAuth().getRole());
                    parents[i].setPermission(responses[i].getAuth().getPermission());
                    parents[i].setRange(responses[i].getAuth().getRange());
                }
                DatabaseManager.getInstance(BabynoticeActivity.this).deleteAllParents(babyId);
                DatabaseManager.getInstance(BabynoticeActivity.this).insertOrReplaceInTxParent(parents);

                myAdapter.notifyDataSetChanged();
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {

            }
        });
    }

    private static boolean isNetworkConnect(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING) {
            return true;
        } else if (conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) {
            return false;
        }
        return false;
    }

    @Override
    public void onClickLeft() {
        onBackPressed();
    }

    @Override
    public void onClickRight() {
        if (babyAndParent.getRole() == 0) { // 成员
            Intent intent = new Intent(BabynoticeActivity.this, NormalInviteActivity.class);
            startActivity(intent);
        } else { // 管理员,超级管理员
            Intent intent = new Intent(BabynoticeActivity.this, AdminInviteActivity.class);
            startActivity(intent);
        }
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            View view = null;
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                view = View.inflate(BabynoticeActivity.this, R.layout.item_baby_all_new, null);

                // 设置按下的颜色反馈
                StateListDrawable drawable = new StateListDrawable();
                drawable.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(view.getResources().getColor(R.color.theme_bg)));
                drawable.addState(StateSet.NOTHING, new ColorDrawable(view.getResources().getColor(android.R.color.white)));
                view.setBackgroundDrawable(drawable);

                holder.roundedImageView = (RoundedImageView) view.findViewById(R.id.iv_head_baby_new_all);
                holder.tv_chengwei = (CuteTextView) view.findViewById(R.id.tv_chengwei);
                holder.tv_quanxian = (CuteTextView) view.findViewById(R.id.tv_quanxian);
                holder.imageView = (ImageView) view.findViewById(R.id.iv_gonext);
//                holder.imageView = (ImageView) view.findViewById(R.id.iv_blue_selected);
                holder.bottomLineView = view.findViewById(R.id.bottom_line);
                view.setTag(holder);
            } else {
                view = convertView;
                holder = (ViewHolder) view.getTag();
            }
//


            holder.tv_chengwei.setText(list.get(position).getName());
            if (list.get(position).getAuth().getRole() == 2) {
                holder.tv_quanxian.setText("大家长");
            } else if (list.get(position).getAuth().getRole() == 1) {
                holder.tv_quanxian.setText("家长");
            } else if (list.get(position).getAuth().getRole() == 0) {
                holder.tv_quanxian.setText("成员");
            }

            ImageLoader.getInstance().displayImage(list.get(position).getPath(), holder.roundedImageView, options);
//            if (isAdmin) {
//                holder.imageView.setVisibility(View.VISIBLE);
//            } else {
////                if (list.get(position).getPhone() == loginInfo.getPhone()) {
////                    holder.imageView.setVisibility(View.VISIBLE);
////                }else{
////                    holder.imageView.setVisibility(View.GONE);
////                }
//                holder.imageView.setVisibility(View.GONE);
//            }
            return view;
        }

        class ViewHolder {
            CuteTextView tv_chengwei, tv_quanxian;
            ImageView imageView;
            RoundedImageView roundedImageView;
            View bottomLineView;
        }
    }

    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_head_circle_default_small)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.drawable.ic_head_circle_default_small)  //image连接地址为空时
                .showImageOnFail(R.drawable.ic_head_circle_default_small)  //image加载失败
                .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();
    }

}
